package com.engine.core.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;

public class XPathUtil {

    private  Document document;
    private  XPath xpath;


    private static Logger logger= LoggerFactory.getLogger(JdbcTemplateUtils.class);

    private XPathUtil(){}


    public static XPathUtil  createXPath(InputStream inputData){
        // 创建Document对象
        try {
            XPathUtil xpathUtil = new XPathUtil();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setValidating(false);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            xpathUtil.document=documentBuilder.parse(inputData);

            // 创建XPath对象
            XPathFactory factory = XPathFactory.newInstance();
            xpathUtil.xpath = factory.newXPath();
            return xpathUtil;
        } catch (Exception e) {
            logger.error("createXPath error!",e);
        }
        return null;
    }

    public static XPathUtil createXPath(String inputData, String encoding){
         try {
             InputStream inputStream = new ByteArrayInputStream(inputData.getBytes(encoding));
             return createXPath(inputStream);
         }catch (Exception e) {
             logger.error("createXPath error!",e);
         }
         return null;
    }

    public static XPathUtil createXPath(String inputData, Charset encoding){
        try {
            Charset.defaultCharset();
            InputStream inputStream = new ByteArrayInputStream(inputData.getBytes(encoding));
            return createXPath(inputStream);
        }catch (Exception e) {
            logger.error("createXPath error!",e);
        }
        return null;
    }

    public static XPathUtil createXPath(String inputData){
        try {
            Charset.defaultCharset();
            InputStream inputStream = new ByteArrayInputStream(inputData.getBytes());
            return createXPath(inputStream);
        }catch (Exception e) {
            logger.error("createXPath error!",e);
        }
        return null;
    }

    public String getValue(String xpathStr){
        try {
            return xpath.evaluate(xpathStr, document);
        } catch (Exception e) {
            logger.error("getValue error!",e);
        }
        return null;
    }

    // 获取子元素并打印
    public NodeList  getNodeList(String xpathStr) {
        try {
            return (NodeList) xpath.evaluate(xpathStr, document,
                    XPathConstants.NODESET);
        } catch (Exception e) {
            logger.error("getValue error!",e);
        }
        return null;
    }

    public Node getNode(String xpathStr) {
        try {
            return (Node) xpath.evaluate(xpathStr, document,
                    XPathConstants.NODE);
        } catch (Exception e) {
            logger.error("getValue error!",e);
        }
        return null;
    }

    public static void main(String[] args) {
          String xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                  "<rss version=\"2.0\">\n" +
                  "    <channel>\n" +
                  "        <title>Java Tutorials and Examples 2</title>\n" +
                  "        <language>en-us</language>\n" +
                  "        <item>\n" +
                  "            <title><![CDATA[Java Tutorials 2]]></title>\n" +
                  "            <link>http://www.javacodegeeks.com/</link>\n" +
                  "        </item>\n" +
                  "        <item>\n" +
                  "            <title><![CDATA[Java Examples 21 ]]></title>\n" +
                  "            <link>http://examples.javacodegeeks.com/</link>\n" +
                  "        </item>\n" +
                  "    </channel>\n" +
                  "    <college name=\"c1\">\n" +
                  "        <class name=\"class1\">\n" +
                  "            <student name=\"stu1\" sex='male' age=\"21\" />\n" +
                  "            <student name=\"stu2\" sex='female' age=\"20\" />\n" +
                  "            <student name=\"stu3\" sex='female' age=\"20\" />\n" +
                  "        </class>\n" +
                  "    </college>\n" +
                  "    <bookstore>\n" +
                  "        <book>\n" +
                  "            <title lang=\"eng\">Harry Potter</title>\n" +
                  "            <price>29.99</price>\n" +
                  "        </book>\n" +
                  "        <book>\n" +
                  "            <title lang=\"eng\">Learning XML</title>\n" +
                  "            <price>39.95</price>\n" +
                  "        </book>\n" +
                  "    </bookstore>\n" +
                  "</rss>";

        XPathUtil xpathUtil =  XPathUtil.createXPath(xml);
        Node node=xpathUtil.getNode("/rss/channel/title");
        System.out.println(node.getTextContent());

        NodeList nodeList=xpathUtil.getNodeList("/rss/channel/item[2]/title");
        System.out.println(nodeList.getLength());
        System.out.println(nodeList.item(0).getChildNodes().item(0).getNodeValue());
    }


}
